<!--
- File:    共享花园的编辑页面.
-->
<template>
  <div class="Web_Box">
    <div class="bg_fff">
      <div class="add_time f-cb"><span class="fl">花园名称</span>
        <input type="text" class="g_ipts" placeholder="输入花园名称" v-model="gardenName"></div>
      <div class="add_time f-cb" @click="switchAreaSelectShow(true)"><span class="fl">所在地区</span>
        <span class="fr"><span class="vm" style="color: #595757;">{{addressTxt || '选择所在地区'}}</span><i class="iconfont icon-more"></i></span>
      </div>
      <div class="Fillinformation" style="padding: 0;border-bottom: 1px #eee solid">
        <div class="Fill_input f-cb" style="color: #221814; background: #fff;margin-bottom: 0">
          <label>共享开始时间<span type="text" @click="openBeginDatePicker" style="float: right">{{beginDate == null ? '点击选择时间' : beginDate}}</span></label>
        </div>
      </div>
      <div class="Fillinformation" style="padding: 0; margin-top: 0;border-bottom: 1px #eee solid">
        <div class="Fill_input f-cb" style="color: #221814; background: #fff">
          <label>共享结束时间<span type="text" @click="openEndDatePicker" style="float: right">{{endDate == null ? '点击选择时间' : endDate}}</span></label>
        </div>
      </div>
      <div class="add_time f-cb"><span class="fl">备注</span>
        <input type="text" class="g_ipts" placeholder="输入备注" v-model="remark"></div>
      <div class="edittext">
        <div class="fll_price2 f-cb">
          <div class="fllimg" v-show="gardenImg ==''">
            <div id="select-pic">
              <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
            </div>
            <i class="iconfont icon-tianjia1" @click="getImg" style="pointer-events: auto"></i>
          </div>
          <div class="fllimg" v-if="gardenImg && gardenImg !='' ">
            <img :src="$config.imgsite + $config.uploadImgSrc + gardenImg + '_w200'" @click="getImg"></div>
        </div>
      </div>
    </div>
    <div class="add_gran2"><a class="add_btn2" @click="updateGardenInfo">提交</a></div>
    <vue-area :props-show="areaSelectShow" :props-result="areaResult" v-on:result="areaSelected"></vue-area>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
    <datetime-picker
      ref="beginDatePicker"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleBeginDateChange">
    </datetime-picker>
    <datetime-picker
      ref="endDatePicker"
      :startDate="new Date()"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleEndDateChange">
    </datetime-picker>
  </div>
</template>

<script>
  import vueArea from '../../components/area'
  import {Actionsheet} from 'mint-ui'
  import DatetimePicker from '../../components/dateTimePicker'

  export default{
    data() {
      return {
        gardenId: this.$route.params.id,
        beginDate: null,
        endDate: null,
        gardenName: '',
        remark: '',
        gardenImg: '',
        areaSelectShow: false,
        areaResult: {province: {code: '', name: ''}, city: {code: '', name: ''}, area: {code: '', name: ''}},
        sheetVisible: false,
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }]
      }
    },
    components: {
      'vue-area': vueArea,
      'mt-actionsheet': Actionsheet,
      'datetimePicker': DatetimePicker
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      // this.$native.weixinShare(window.location.href)
      this.getGardenInfo()
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    computed: {
      addressTxt: function () {
        if (this.areaResult.province.name == '') {
          return ''
        }
        return this.areaResult.province.name + ' ' + this.areaResult.city.name + ' ' + this.areaResult.area.name
      }
    },
    methods: {
      openBeginDatePicker() {
        this.$refs.beginDatePicker.open()
      },
      openEndDatePicker() {
        this.$refs.endDatePicker.open()
      },
      handleBeginDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.beginDate = dateStr
      },
      handleEndDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.endDate = dateStr
      },
      getImg() {
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          wx.chooseImage({ // eslint-disable-line
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              var localId = res.localIds[0]
              wx.getLocalImgData({ // eslint-disable-line
                localId: localId,
                success: (res) => {
                  var localData = res.localData
                  localData = localData.replace('jgp', 'jpeg')
                  if (localData.indexOf('data:image/jpeg;base64,') == -1) {
                    localData = 'data:image/jpeg;base64,' + localData
                  }
                  this.$indicator.open('上传图片中...')
                  this.$request.uploadImg(localData).then(data => {
                    this.gardenImg = data[0]
                  }).catch(e => {
                    this.$toast('上传图片失败:' + e.msg)
                  }).finally(() => {
                    this.$indicator.close()
                  })
                }
              })
            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      getGardenInfo() {
        this.$request.getShareGardenInfo(this.gardenId).then(data => {
          this.beginDate = data.start_time && this.$utils.timestampToDate(data.start_time, 'yyyy-MM-dd')
          this.endDate = data.start_time && this.$utils.timestampToDate(data.end_time, 'yyyy-MM-dd')
          this.gardenName = data.garden_name
          this.remark = data.remark
          this.gardenImg = data.cover_img
          this.areaResult.province.code = data.province_id
          this.areaResult.province.name = data.province_name
          this.areaResult.city.code = data.city_id
          this.areaResult.city.name = data.city_name
          this.areaResult.area.code = data.area_id
          this.areaResult.area.name = data.area_name
        })
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      updateGardenInfo() {
        if (this.gardenName.trim() == '') {
          this.$toast('请输入花园名称')
          return
        }
        if (this.areaResult.province.code == '' || this.areaResult.city.code == '' || this.areaResult.area.code == '') {
          this.$toast('请先选择所在地区')
          return
        }
//        if (this.gardenImg == '') {
//          this.$toast('请添加花园封面图')
//          return
//        }
        let param = {
          sg_id: this.gardenId,
          area_id: this.areaResult.area.code,
          city_id: this.areaResult.city.code,
          cover_img: this.gardenImg,
          garden_name: this.gardenName,
          province_id: this.areaResult.province.code,
          start_time: this.beginDate,
          end_time: this.endDate,
          remark: this.remark
        }
        this.$request.updateShareGardenInfo(param).then(data => {
          this.$toast('修改花园信息成功')
          this.$router.go(-1)
        })
      },
      delImg() {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.gardenImg = ''
        }).catch(() => {})
      },
      switchAreaSelectShow(boolValue) {
        this.areaSelectShow = boolValue
      },
      areaSelected(areaSelectShow, result) {
        this.areaSelectShow = areaSelectShow
        this.areaResult = result
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$request.uploadImg(imgDataUrl).then(data => {
                this.gardenImg = data[0]
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      }
    }
  }
</script>

<style>

</style>